import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import * as THREE from 'three'
import Validator from '../validator'

const Loader = (Arr = []) => {
  const _Arr = Arr.map(item => {
    if (Validator.isString(item)) {
      return { path: item, doubleSide: true }
    } else {
      return item
    }
  })

  const promiseArr = []
  for (let i = 0; i < _Arr.length; i++) {
    const _promise = new Promise((resolve, reject) => {
      const loader = new GLTFLoader()
      // 定义解析加载器
      const dracoLoader = new DRACOLoader()
      dracoLoader.setDecoderPath('draco/') // 存放draco文件的路径
      dracoLoader.preload()
      loader.setDRACOLoader(dracoLoader)
      loader.load(
        _Arr[i].path,
        gltf => {
          if (_Arr[i].doubleSide) {
            const gletScene = gltf.scene || gltf.scenes[0]
            gletScene.traverse((child) => {
              if (child.type === 'Mesh') {
                child.material.side = THREE.DoubleSide
              }
            })
            resolve(gltf)
          } else {
            resolve(gltf)
          }
        },
        null,
        error => reject(error)
      )
    })
    promiseArr.push(_promise)
  }
  return new Promise((resolve, reject) => {
    Promise.all(promiseArr)
      .then(gltfArr => resolve(gltfArr))
      .catch(error => reject(error))
  })
}

export default Loader
